from utils import debug_info
import gc
import _thread


class TCPServer:
	def __init__(self, host, port, path, player, callback: callable()):
		import socket
		from config import Config

		host = socket.getaddrinfo(host, port)[0][-1]

		self._path = path
		self._player = player
		self._callback = callback
		self._server = socket.socket()
		# self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

		self._server.connect(host)
		self._server.write(bytes("GET %s HTTP/1.1\r\nHost: walkline.wang\r\nConnection: close\r\n\r\n" % self._path, "utf-8"))
		self._server.setblocking(True)
		# self._stream = self._server.makefile("rb")
		# self._server.bind(host)
		# self._server.listen(1)

		# debug_info("tcp server bind on port %s" % Config.TCP_PORT)
		self._count = 0
		self._player.reset()

	def playback(self, data):
		for i in range(0, round(len(data) / 32)):
			byte = data[i * 32:(i + 1) * 32]
			self._player.play_chunk(byte)

	def start(self):
		from utime import sleep_ms

		# a = "GET /1 HTTP/1.1\r\nHost: http://baidu.com\r\nConnection: close\r\n\r\n"

		while True:
			# sleep_ms(300)

			data = self._server.read(2048)
			# data = self._stream.read(32)
			# self._count += 1

			if not data:
				continue

			# self._callback(data, self._count)

			_thread.start_new_thread(self.playback, (data,))

		# for i in range(0, 4):
			# 	self._player.play_chunk(bytes([data[i*32:32]]))

			# for byte in data:
			# 	self._player.play_chunk(bytes([byte]))

			# client, address = self._server.accept()

			# debug_info("client[%s:%s] connected" % address)
			#
			# request = str(client.recv(1024), "utf-8").strip()
			#
			# if len(request) == 0:
			# 	client.close()
			# 	debug_info("client[%s:%s] disconnected" % address)
			#
			# 	continue
			#
			# debug_info("received tcp request: %s [%s:%s]" % (request, address[0], address[1]))
			#
			# # process client request(control command)
			# self._respond_to_client(client, request)
			# client.close()

			# gc.collect()
